// 定义管理员相关的接口
const express = require('express');
const router = express.Router();
const Joi = require('joi');
const Response = require('../utils/Response.js');

// 引入mysql连接池
const pool = require('../utils/db.js');

// 修改密码，传id
router.post('/admin-update', (req, resp) => {
  let { id, pass } = req.body;
  let schema = Joi.object({
    id: Joi.required(),
    pass: Joi.required(),
  });
  let { err, value } = schema.validate(req.body);
  if (err) {
    resp.send(Response.error(400, err));
    return;
  }
  let sql = `update administor set pass=? where id=?`;
  pool.query(sql, [pass, id], (err, res) => {
    if (err) {
      resp.send(Response.error(500, err));
      throw err;
    }
    resp.send(Response.ok());
  });
});

/**
 * 处理登录业务
 */
router.post('/admin-login', (req, resp) => {
  let { aname, pass } = req.body;
  // 表单验证
  let schema = Joi.object({
    aname: Joi.string().required(), // 必填
    pass: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 查询数据库，账号密码是否填写正确
  let sql = 'select * from administor where aname=? and pass=?';
  pool.query(sql, [aname, pass], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    if (result.length == 0) {
      resp.send(Response.error(1001, '账号密码输入错误'));
    } else {
      resp.send(Response.ok(result));
    }
  });
});

/**
 * 查询所有用户（分页）
 * @param:
 *   {page,pagesize}
 * @return:
 *   {code:200, msg:'ok', data:[]}
 */
router.get('/admin-lists', async (req, resp) => {
  // 获取请求参数   get请求的参数封装在req.query中
  let { page, pagesize } = req.query;

  //TODO 服务端表单验证  如果验证通过那么继续后续业务  如果验证不通过，则直接返回参数异常
  let schema = Joi.object({
    page: Joi.number().required(), // page必须是数字，必填
    pagesize: Joi.number().integer().max(100).required(), // pagesize必须是不大于100的数字，必填
  });
  let { error, value } = schema.validate(req.query);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行查询数组业务
  try {
    let startIndex = (page - 1) * pagesize;
    let size = parseInt(pagesize);
    let sql = 'select * from administor limit ?,?';
    let result = await pool.querySync(sql, [startIndex, size]);
    // 执行查询总条目数
    let sql2 = 'select count(*) as count from administor';
    let result2 = await pool.querySync(sql2, [startIndex, size]);
    let total = result2[0].count;
    resp.send(
      Response.ok({ page: parseInt(page), pagesize: size, total, result })
    );
  } catch (error) {
    resp.send(Response.error(error));
  }
});

/**
 * 添加用户接口
 * @param:
 *   {aname,pass}
 * @return:
 *   {code:200, msg:'ok'}
 */
router.post('/admin-lists/add', async (req, resp) => {
  let { aname, pass } = req.body; // post请求参数在req.body中

  // 表单验证
  let schema = Joi.object({
    aname: Joi.string().required(), // 必填
    pass: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }
  // 表单验证通过，执行添加操作
  let sql = 'insert into administor(aname,pass) values (?,?)';
  pool.query(sql, [aname, pass], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});

/**
 * 删除用户接口
 * @param:
 *   id:   用户id
 * @return:
 *   {code:200, msg:'ok'}
 */
router.post('/admin-lists/del', (req, resp) => {
  let { id } = req.body;

  // 表单验证
  let schema = Joi.object({
    id: Joi.string().required(), // 必填
  });
  let { error, value } = schema.validate(req.body);
  if (error) {
    resp.send(Response.error(400, error));
    return; // 结束
  }

  // 执行删除业务
  let sql = 'delete from administor where id = ?';
  pool.query(sql, [id], (error, result) => {
    if (error) {
      resp.send(Response.error(500, error));
      throw error;
    }
    resp.send(Response.ok());
  });
});

// 将router对象导出
module.exports = router;
